package main

import (
	"strings"
	"time"
	"net/http"
	"global/libs/http/app"
	"strconv"
	"global/model"
	"github.com/ngaut/log"
	"fmt"
	"global/constants"
)

const (
	coinLikeActionAdd = "add"
	coinLikeActionDel = "del"
)

// 添加喜欢
func (h *Handler) OnHandleAddCoinToSearch(writer http.ResponseWriter, request *http.Request) {

	if !h.IsPost() {
		h.Error(app.Err404)
		return
	}

	uid, _ := strconv.Atoi(request.PostFormValue("uid"))
	symbol := strings.ToLower(request.PostFormValue("symbol"))
	action := strings.ToLower(request.PostFormValue("action"))
	if uid <= 0 || symbol == "" || (action != coinLikeActionAdd && action != coinLikeActionDel) {
		h.Error(app.ErrParameter)
		return
	}

	// get coin by symbol
	result, err := model.CoinModel.GetItemBySymbol(symbol)
	if err != nil {
		log.Errorf("Error: %s", err)
		h.Error(app.ErrInnerError)
		return
	}

	if result == nil {
		h.Error(app.ErrCoinNotExists)
		return
	}

	has, err := model.CoinLikeModel.CheckHasUserLiked(uid, result.Id)
	if err != nil {
		log.Errorf("Error: %s", err)
		h.Error(app.ErrInnerError)
		return
	}

	if has && action == coinLikeActionAdd {
		h.Error(app.ErrLikedCoinExists)
		return
	} else if !has && action ==coinLikeActionDel {
		h.Error(app.ErrLikedCoinNotExists)
		return
	}

	switch action {
	case coinLikeActionAdd:
		if result.Id == 0 {
			return
		}
		h.doUserLikeAdd(uid, result)
	case coinLikeActionDel:
		h.doUserLikeDel(uid, result.Id, result.Symbol)
	}

}

func (h *Handler) doUserLikeDel(uid, coinId int, symbol string) {
	_, err := model.CoinLikeModel.DelItem(uid, coinId)
	if err != nil {
		h.Error(app.ErrUnknownError)
		return
	}

	// 修改缓存
	if err = h.flushCoinLikeCache(uid); err != nil {
		log.Errorf("Error: %s", err)
	}

	h.Json(app.AppMsg(map[string]interface{}{
		"uid": uid,
		"symbol": strings.ToUpper(symbol),
		"action": coinLikeActionDel,
	}))

}

// 执行添加到喜欢
func (h *Handler) doUserLikeAdd(uid int, result *model.Coin) {

	userLike := &model.CoinLike{
		Uid: 		uid,
		CoinId: 	result.Id,
		CoinMid: 	result.Mid,
		CoinSymbol: strings.ToLower(result.Symbol),
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}

	_, err := model.CoinLikeModel.AddItem(userLike)
	if err != nil {
		log.Errorf("Error: %s", err)
		h.Error(app.ErrInnerError)
		return
	}

	// 修改缓存
	if err = h.flushCoinLikeCache(uid); err != nil {
		log.Errorf("Error: %s", err)
	}

	h.Json(app.AppMsg(map[string]interface{}{
		"uid": uid,
		"symbol": strings.ToUpper(result.Symbol),
		"action": coinLikeActionAdd,
	}))
}

func (h *Handler) flushCoinLikeCache(uid int) error {
	key := fmt.Sprintf(constants.UserCoinLikeCache, uid)
	conn := h.ctx.GetBaseRedis().Get()
	defer conn.Close()
	if _, err := conn.Do("DEL", key); err != nil {
		return err
	}
	return nil
}